package com.rongsoft.ehcache;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@CacheConfig(cacheNames = "books")
public class BookServiceImpl implements BookService {

    @Override
    @Cacheable(key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
    public Book findBook(String bookId) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("执行方法,不使用缓存:{}",bookId);
        return new Book("1","Query","1");
    }

    @Override
    @CachePut(key = "#root.targetClass.getSimpleName().concat(':').concat(#book.id)")
    public Book savaBook(Book book) {
        return book;
    }

    @Override
    @CacheEvict(key = "#root.targetClass.getSimpleName().concat(':').concat(#bookId)")
    public String deleteBook(String bookId) {
        return bookId;
    }
}
